import requests
from typing import Optional
class APIConfig:
    """
    Configuration class for API endpoints.
    """
    BaseURL="http://127.0.0.1:5000"
    QuestionListURL=BaseURL+"/service/task/gettasks"
    StartTaskTimeURL=BaseURL+"/service/task/starttasktime"
    UserStatusURL=BaseURL+"/service/task/userstatus"
    SubmissionsURL=BaseURL+"/service/task/getsubmissions"
    WritupURL=BaseURL+"/service/task/writup"
    UserInformationURL=BaseURL+"/service/user/getuserinformation"
    WriteupReportURL=BaseURL+"/service/task/writupReport"
    ChatRecordURL=BaseURL+"/service/chat/getchatrecord"
def fetch_data(url:str,params:dict=None, headers:dict=None,timeout:int=5) -> dict:
    """
    Fetch data from a given URL with optional parameters and headers.
    Args:
        url (str): The URL to fetch data from.
        params (dict, optional): Query parameters to include in the request.
        headers (dict, optional): Headers to include in the request.
        timeout (int, optional): The timeout for the request in seconds.
    Returns:
        dict: The JSON response from the server.
    """
    retry_count = 0
    max_retries = 3
    while retry_count < max_retries:
        try:
            response = requests.get(url, params=params, headers=headers, timeout=timeout)
            response.raise_for_status() 
            return response.json()
        except requests.exceptions.RequestException as e:
            retry_count += 1
            print(f"请求失败: {e}，重试 {retry_count}/{max_retries}...")
            if retry_count == max_retries:
                raise
def get_question_list(url:str=APIConfig.QuestionListURL, params:dict=None, headers:dict=None) -> list:
    """
    Get a list of questions from the specified URL.
    Args:
        url (str): The URL to fetch the question list from.
        params (dict, optional): Query parameters to include in the request.
        headers (dict, optional): Headers to include in the request.
    Returns:
        list: A list of question objects.
    """
    retry_count = 0
    max_retries = 3
    while retry_count < max_retries:
        try:
            response = requests.get(url, params=params, headers=headers)
            response.raise_for_status() 
            return response.json().get("questions", [])
        except requests.exceptions.RequestException as e:
            retry_count += 1
            print(f"请求失败: {e}，重试 {retry_count}/{max_retries}...")
            if retry_count == max_retries:
                raise
def get_start_task_time(url:str=APIConfig.StartTaskTimeURL, params:dict=None, headers:dict=None) -> Optional[str]:
    """
    Start the task time for the current user.
    Args:
        url (str): The URL to start the task time from.
        params (dict, optional): Query parameters to include in the request.
        headers (dict, optional): Headers to include in the request.
    Returns:
        datetime: The start time of the task.
    """
    retry_count = 0
    max_retries = 3
    while retry_count < max_retries:
        try:
            response = requests.get(url, params=params, headers=headers)
            response.raise_for_status() 
            return response.json().get("start_time", None)
        except requests.exceptions.RequestException as e:
            retry_count += 1
            print(f"请求失败: {e}，重试 {retry_count}/{max_retries}...")
            if retry_count == max_retries:
                raise
def get_user_status(url:str=APIConfig.UserStatusURL, params:dict=None, headers:dict=None) -> list:
    """
    Get the status of the current user.
    Args:
        url (str): The URL to fetch the user status from.
        params (dict, optional): Query parameters to include in the request.
        headers (dict, optional): Headers to include in the request.
    Returns:
        list: The user score and rank day by day.
    """
    retry_count = 0
    max_retries = 3
    while retry_count < max_retries:
        try:
            response = requests.get(url, params=params, headers=headers)
            response.raise_for_status() 
            return response.json().get("user_status", [])
        except requests.exceptions.RequestException as e:
            retry_count += 1
            print(f"请求失败: {e}，重试 {retry_count}/{max_retries}...")
            if retry_count == max_retries:
                raise
def get_submissions(url:str=APIConfig.SubmissionsURL, params:dict=None, headers:dict=None) -> list:
    """
    Get the submissions for the current user.
    Args:
        url (str): The URL to fetch the submissions from.
        params (dict, optional): Query parameters to include in the request.
        headers (dict, optional): Headers to include in the request.
    Returns:
        list: A list of submission objects.
    """
    retry_count = 0
    max_retries = 3
    while retry_count < max_retries:
        try:
            response = requests.get(url, params=params, headers=headers)
            response.raise_for_status() 
            return response.json().get("submissions", [])
        except requests.exceptions.RequestException as e:
            retry_count += 1
            print(f"请求失败: {e}，重试 {retry_count}/{max_retries}...")
            if retry_count == max_retries:
                raise
def get_writup(url:str=APIConfig.WritupURL, params:dict=None, headers:dict=None) -> str:
    """
    Get the write-up for the current user.
    Args:
        url (str): The URL to fetch the write-up from.
        params (dict, optional): Query parameters to include in the request.
        headers (dict, optional): Headers to include in the request.
    Returns:
        str: The write-up for the current user.
    """
    retry_count = 0
    max_retries = 3
    while retry_count < max_retries:
        try:
            response = requests.get(url, params=params, headers=headers)
            response.raise_for_status() 
            return response.json().get("writup", "")
        except requests.exceptions.RequestException as e:
            retry_count += 1
            print(f"请求失败: {e}，重试 {retry_count}/{max_retries}...")
            if retry_count == max_retries:
                raise
def get_user_information(url:str=APIConfig.UserInformationURL, params:dict=None, headers:dict=None) -> dict:
    """
    Get the user information for the current user.
    Args:
        url (str): The URL to fetch the user information from.
        params (dict, optional): Query parameters to include in the request.
        headers (dict, optional): Headers to include in the request.
    Returns:
        dict: The user information for the current user.
    """
    retry_count = 0
    max_retries = 3
    while retry_count < max_retries:
        try:
            response = requests.get(url, params=params, headers=headers)
            response.raise_for_status() 
            return response.json().get("user_information", {})
        except requests.exceptions.RequestException as e:
            retry_count += 1
            print(f"请求失败: {e}，重试 {retry_count}/{max_retries}...")
            if retry_count == max_retries:
                raise
def get_exist_writeup_report(url:str=APIConfig.WriteupReportURL,params:dict=None, headers: Optional[dict] = None) -> dict:
    """
    Get the existing write-up report from the database for a specific user and question.
    Args:
        user_id (str): The ID of the user.
        question_id (str): The ID of the question.
        headers (dict, optional): Headers to include in the request.
    Returns:
        dict: The write-up report for the user and question.
    """
    retry_count = 0
    max_retries = 3
    while retry_count < max_retries:
        try:
            response = requests.get(url, params=params, headers=headers)
            response.raise_for_status() 
            return response.json()
        except requests.exceptions.RequestException as e:
            retry_count += 1
            print(f"请求失败: {e}，重试 {retry_count}/{max_retries}...")
            if retry_count == max_retries:
                raise
            if retry_count == max_retries:
                raise
def get_chat_record(url:str=APIConfig.ChatRecordURL, params:dict=None, headers: Optional[dict] = None) -> list:
    """
    Get the chat record for a specific user and question.
    Args:
        params (dict): Parameters containing user_id and question_id.
        headers (dict, optional): Headers to include in the request.
    Returns:
        list: A list of chat messages for the user and question.
    """
    retry_count = 0
    max_retries = 3
    while retry_count < max_retries:
        try:
            response = requests.get(url, params=params, headers=headers)
            response.raise_for_status() 
            return response.json()
        except requests.exceptions.RequestException as e:
            retry_count += 1
            print(f"请求失败: {e}，重试 {retry_count}/{max_retries}...")
            if retry_count == max_retries:
                raise
